<!-- 事件统计分析-->

<template>
    <!-- 报表检索条件组件 -->
    <ReportSearch :loading="loading" :searchFormDatas="searchFormDatas" v-model:searchForm="searchForm"
        @handleSearchForm="handleSearchForm" @handleResetForm="handleResetForm">
        <span class="searchBtn" :class="{'forbidBtn': loading}" @click="changeTableType()">{{ tableType === '1'? '图表' : '表格'}}</span>
    </ReportSearch>
    <!-- 报表表格标题组件-->
    <ReportTableTitle :tableTitle="tableTitle" />
    <!-- 报表表格组件-->
    <ReportTable :loading="loading" :tableData="tableData" :pageInfo="pageInfo"
        :summaryData="summaryData" :tableColumnData="tableColumnData" :tableColumnWidthData="tableColumnWidthData" />
    <!-- 报表表格分页组件-->
    <ReportTablePage v-model:pageInfo="pageInfo" @handleSearchForm="handleSearchForm" />
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import moment from 'moment';

import ReportSearch from '@/components/reportSearch/index.vue';
import ReportTableTitle from '@/components/reportTableTitle/index.vue';
import ReportTable from '@/components/reportTable/index.vue';
import ReportTablePage from '@/components/reportTablePage/index.vue';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/technicalDataAnalysis';
import * as basicServer from '@/api/modules/common';

import { getYesterday } from '@/utils/date';
import { apiFn, deepCopy } from '@/utils/utilFns';

// 报表表格标题
const defaultTitle = '事件统计分析';
const tableTitle = ref(defaultTitle);

// 默认表单数据
const defaultSearchForm = {
    orgNames: local.getItem('defaultOrgNodes'),
    orgIds: local.getItem('defaultOrgIds'),
    timeFrame: [`${getYesterday(0)} 00:00:00`, `${getYesterday(0)} 23:59:59`],
    vehicleNumber: '',
    eventCategory: '',
    eventModule: [],
    eventType: [],
    eventCode: []
};

// 默认分页数据
const defaultPageInfo = {
    currentPage: 1,
    pageSize: 20,
    total: 0
};

// 加载状态
const loading = ref(false);
const tableType = ref('1');

// 表头数据
const tableColumnData = ref([]);

// 表格数据
const tableData = ref([]);

// 表头宽度数据
const tableColumnWidthData = {
    takeoverTime: '150',
};

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'selectTree',
        label: '所属组织',
        prop: 'orgIds',
        options: [],
        api: () => { },
        placeholder: '请选择所属组织',
        rules: [{ required: true, message: '请选择所属组织', trigger: ['blur, change'] }]
    },
    {
        id: 1,
        type: 'dateTimeRangePicker',
        prop: 'timeFrame',
        label: '时间范围',
        options: [],
        api: () => { },
        placeholder: '请选择时间范围',
        rules: [{ required: true, message: '请选择时间范围', trigger: ['change'] }]
    },
    {
        id: 2,
        type: 'select',
        prop: 'eventCategory',
        label: '事件分类',
        clearable: false,
        options: [{ label: '车端', value: '0' }, { label: '平台服务', value: '1' }],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 3,
        type: 'selectMulti',
        prop: 'eventModule',
        label: '模块名称',
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 4,
        type: 'selectMulti',
        prop: 'eventType',
        label: '事件类型',
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 5,
        type: 'select',
        prop: 'vehicleNumber',
        label: '设备编号',
        options: [],
        api: () => { },
        placeholder: '请选择',
        rules: [{ required: true, message: '请选择', trigger: ['change'] }]
    },
    {
        id: 6,
        type: 'selectMulti',
        prop: 'eventCode',
        label: '事件排除',
        options: [],
        api: () => { },
        placeholder: '请输入',
    }
]);

// 表单数据
const searchForm = reactive(deepCopy(defaultSearchForm));

// 分页数据
const pageInfo = reactive(deepCopy(defaultPageInfo));

// 汇总数据
const summaryData = ref({});

onMounted(() => {
    getModuleNameOptions();
    getEventTypeOptions();
    getEquipNumberOptions();
    getDefaultTime();
});

// 所属组织变化监听
watch(() => searchForm.orgIds, () => {
    searchForm.vehicleNumber = '';
    getEquipNumberOptions();
});

// 获取默认时间
const getDefaultTime = () => {
	const timeStamp = new Date().getTime();
	const end = moment(timeStamp).format('YYYY-MM-DD HH:mm:ss');
	const start = moment(timeStamp - 3600 * 1000).format('YYYY-MM-DD HH:mm:ss');
	searchForm.timeFrame = [start, end];
};

const changeTableType = () => {
    tableType.value = tableType.value === '1' ? '2' : '1';
};

// 获取模块名称
const getModuleNameOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_event_module' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[3]['options'] = data;
            } 
        }).catch(() => {
            searchFormDatas.value[3]['options'] = [];
        });
};

// 获取事件类型
const getEventTypeOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_event_type' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[4]['options'] = data;
            } 
        }).catch(() => {
            searchFormDatas.value[4]['options'] = [];
        });
};

// 获取设备编号
const getEquipNumberOptions = () => {
    let params = {
        like: { orgId: searchForm.orgIds },
        equal: { vehicleCategory: '1' }
    };

    apiFn(basicServer.getNumberList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[5]['options'] = data
            }
        }).catch(() => {
            searchFormDatas.value[5]['options'] = [];
        });
};

// 获取查询参数
const getParams = () => {
    const { orgIds, timeFrame, orgNames, vehicleNumber, eventModule, eventType, eventCategory, eventCode } = searchForm;
    const { pageSize, currentPage } = pageInfo;
    
    const vehicleNo = getVehicleNo(vehicleNumber);

    const params = {
        equal: {
            orgId: orgIds,
			mineName: orgNames,
			vin: vehicleNumber,
			vehicleNum: vehicleNo,
			eventModule: eventModule.join(','),
			eventType: eventType.join(','),
			eventCategory,
			startDate: timeFrame[0],
			endDate: timeFrame[1],
			eventCode: eventCode.join(',')
        },
        limit: pageSize,
        page: currentPage,
    };

    return params;
};

// 获取车辆编号
const getVehicleNo = (vin) => {
    const options = searchFormDatas.value[5]['options'];
    
    const target = options.find(item => item.value === vin);
    
    const vehicleNo = target? target.value : '';
    
    return vehicleNo;
};

// 获取报表表头
const getTableColumn = () => {
    const params = getParams();
    apiFn(server.getEventTableColumn, params)
        .then(res => {
            const { code, data = [], resultMsg = '' } = res;
            if (code === '200') {
                tableColumnData.value = data;
                tableTitle.value = resultMsg;
                getTableList();
            } else {
                tableColumnData.value = [];
                tableTitle.value = defaultTitle;
            }
        }).catch(() => {
            tableColumnData.value = [];
            tableTitle.value = defaultTitle;
        })
};

// 获取报表列表内容
const getTableList = () => {
    const params = getParams();
    loading.value = true;
    apiFn(server.getEventTableList, params)
        .then(res => {
            const { code, data, recordsTotal } = res;
            if (code === '200') {
                if (data.length > 0) {
                    tableData.value = data;
                } else {
                    tableData.value = [];
                }

                pageInfo.total = recordsTotal;
            }
        }).catch(() => {
            tableData.value = [];
            pageInfo.total = 0;
        }).finally(() => {
            loading.value = false;
        })
};

// 查询
const handleSearchForm = (type) => {
    if (loading.value) return;

    if (type === 'search') {
        Object.keys(defaultPageInfo).forEach(key => {
            if (key in pageInfo) {
                pageInfo[key] = defaultPageInfo[key];
            }
        })
    }
    getTableColumn();
};

// 导出
const handleExport = (cb) => {
    if (!tableData.value.length) {
        ElMessage.warning('无查询数据导出!');
        return;
    }
    
    const equal = getParams().equal;
    const { startDate, endDate, vin, orgId } = equal;
    
    const params = {
        equal: {
            ...equal,
            createUser: local.getUser().id,
            exportStartTime: startDate,
            exportEndTime: endDate
        }
    };
    
    apiFn(server.addEventTask, params)
        .then(res => {
            const { code } = res;
            if (code === '200') {
                cb && cb({ orgId, vin });
                ElMessage.success('添加成功!');
            }
        }).catch(() => {
            ElMessage.error('导出事件添加失败!');
        })
   
};

// 重置
const handleResetForm = () => {
    Object.keys(searchForm).forEach(key => {
        if (key in defaultSearchForm) {
            searchForm[key] = defaultSearchForm[key];
        }
    });

    Object.keys(defaultPageInfo).forEach(key => {
        if (key in pageInfo) {
            pageInfo[key] = defaultPageInfo[key];
        }
    });
    
    getDefaultTime();

    tableTitle.value = defaultTitle;
    tableColumnData.value = [];
    tableData.value = [];
};

defineExpose({ handleExport });
</script>

<style lang="scss" scoped></style>